//
//  MeViewController.m
//  1243
//
//  Created by 我的 on 16/3/22.
//  Copyright © 2016年 1243. All rights reserved.
//

#import "MeViewController.h"
#import "TableViewCell.h"
#import "LoginViewController.h"
#import "jiFenViewController.h"
#import "HeaderView.h"
#import "ZhangHuYuECell.h"
#import "ThreeButtonCell.h"
#import "XiaoFeiViewController.h"
#import "FenSiZhongXinTableViewController.h"
#import "ZhuanZhangViewController.h"
#import "BuyQuanViewController.h"
#import "ShopQuanViewController.h"
#import "ReadLoginData.h"
#import "GetAddressTableViewController.h"
#import "MyOrderTableViewController.h"
#import "JudgeUserLogInTool.h"
#import "NetWorkTools.h"
#import "JiuDianHuiWuViewController.h"

@interface MeViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *dataArr;
@property (nonatomic, strong)UIView *top;
@property (nonatomic, strong) HeaderView *headerView;

@property (nonatomic,strong) NSDictionary *loadUserData;

@property (nonatomic,copy)NSString *gouWuQuanCount;

@end

@implementation MeViewController

- (NSDictionary *)loadUserData {
    if (!_loadUserData) {
        _loadUserData = [NSDictionary dictionary];
    }
    return _loadUserData;
    
}

- (HeaderView *)headerView {
    
    if (!_headerView) {
        _headerView = [HeaderView loadHeaderView];
    }
    return _headerView;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.dataArr = [[NSMutableArray alloc] init];
    [self.dataArr addObject:@"我的点赚"];
    [self.dataArr addObject:@"粉丝中心"];
    [self.dataArr addObject:@"地址管理"];
    [self.dataArr addObject:@"我的订单"];
    [self.dataArr addObject:@"我的收藏"];
    [self.dataArr addObject:@"咨询与反馈"];
    [self loadGouWuQuanCount];
    [self loadNewData];
    NSLog(@"%@",self.loadUserData);
    

}

- (void)loadNewData {
    NSDictionary *dict = @{
                           @"PhoneNum":[ReadLoginData readLoginData][@"UserName"],
                           @"Password":[ReadLoginData readLoginData][@"Password"]
                           };
    
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:dict AndMenthodName:@"USERLOGIN" completeBlock:^(id object) {
        
        NSDictionary *loginDict = [NetWorkTools dictionaryWithJsonString:[object objectForKey:@"BackData"]];
        [self cleanloginData];
        [ReadLoginData savelogindataToLocal:loginDict];
        
        self.loadUserData = [ReadLoginData readLoginData];
        
        [self.tableView reloadData];
        
        [self reloadHeaderViewData];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
     //61 116 231
    [self creat];
    
//    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"hy_set"] highImage:[UIImage imageNamed:@"hy_set"] target:self action:@selector(setBtn) imageEdgeInsets:UIEdgeInsetsMake(0, 35, 0, 0) titleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0) title:nil];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZhangHuYuECell" bundle:nil] forCellReuseIdentifier:@"ZhangHuCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ThreeButtonCell" bundle:nil] forCellReuseIdentifier:@"ButtonCell"];
}

- (void)loadGouWuQuanCount {
    NSDictionary *dict = [ReadLoginData readLoginData];
    
    if (dict.count) {
        
        NSString *userId = [dict objectForKey:@"Number"];
        
        NSDictionary *params = @{
                                 @"UserNumber":userId
                                 };
        
        [[NetWorkTools sharedNetWorkTools] objectWithURLDict:params     AndMenthodName:@"BUYCARDCOUNT" completeBlock:^(id object) {

            self.gouWuQuanCount = [object objectForKey:@"BackData"];
            
            [self.tableView reloadData];
        }];
    }
}

- (void)creat{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor whiteColor];
    
    UIImageView *imageView = [[UIImageView alloc] init];
//    imageView.image = [UIImage imageNamed:@"引导页1"];
    [imageView setFrame:self.headerView.bounds];
    [self.headerView addSubview:imageView];
    
    [self.headerView.LoginBtn addTarget:self action:@selector(clickLogin) forControlEvents:UIControlEventTouchUpInside];

    self.headerView.userImageV.layer.cornerRadius = 30;
    self.headerView.userImageV.layer.masksToBounds = YES;
//    self.headerView.backgroundColor = [UIColor colorWithRed:44 / 255.0 green:87 / 255.0 blue:229 / 255.0 alpha:1];
#warning 修改个人中心蓝色背景
    self.tableView.tableHeaderView = self.headerView;
    
}

- (void)setBtn {
    
}

#pragma mark - 点击登录按钮
- (void)clickLogin {
    
    if ([ReadLoginData readLoginData].count) {
        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您将退出当前账号" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        alview.tag = 210;
        [alview show];
        
        
    } else {
        [self presentViewController:[[LoginViewController alloc] init] animated:YES completion:nil];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (alertView.tag == 210) {
        NSLog(@"%ld",buttonIndex)
        
        if (buttonIndex == 0) {
            [self cleanloginData];
            [ReadLoginData removeDataToLocal:@"addressData.plist"];
            [ReadLoginData removeDataToLocal:@"shopData.plist"];
            self.loadUserData = nil;
            [self.tableView reloadData];
            [self reloadHeaderViewData];
            LoginViewController *a = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:[NSBundle mainBundle]];
            [self presentViewController:a animated:YES completion:^{
                
            }];
        } else {
            [self reloadHeaderViewData];
        }
        
    }
    
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    NSLog(@"%ld",self.loadUserData.count);
    [self.tableView reloadData];
}



- (void)cleanloginData {
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *path=[paths objectAtIndex:0];
    //    NSLog(@"path = %@",path);
    NSString *filename=[path stringByAppendingPathComponent:@"loginData.plist"];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dic writeToFile:filename atomically:YES];
    
}

#pragma mark - UITableView Data Source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 3) {
        return self.dataArr.count;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 || indexPath.section == 1) {
     
        ZhangHuYuECell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZhangHuCell" forIndexPath:indexPath];
        if (indexPath.section == 0) {
            
            if (self.loadUserData.count) {
                cell.numLabel.text = [NSString stringWithFormat:@"%.2f",[[self.loadUserData objectForKey:@"Money"] floatValue]];
                
            } else {
                cell.numLabel.text = @"0.00";
            }
            [cell.jiFenJiaoYiButton setTitle:@"酒店会晤" forState:UIControlStateNormal];
            [cell.jiFenJiaoYiButton addTarget:self action:@selector(didClickJiuDianHuiWuButton) forControlEvents:UIControlEventTouchUpInside];
            [cell.leftBtn addTarget:self action:@selector(zhuanzhangBtn) forControlEvents:UIControlEventTouchUpInside];
            [cell.rightBtn addTarget:self action:@selector(buyQuanBtn) forControlEvents:UIControlEventTouchUpInside];
            
        } else {
            cell.titleName.text = @"广告分红积分：";
            if (self.loadUserData.count) {
                cell.numLabel.text = [NSString stringWithFormat:@"%.2f",[[self.loadUserData objectForKey:@"fh_Money"] floatValue]];
            } else {
                cell.numLabel.text = @"0.00";
            }
            [cell.jiFenJiaoYiButton setTitle:@"积分交易" forState:UIControlStateNormal];
            [cell.leftBtn setTitle:@"积分消费" forState:UIControlStateNormal];
            [cell.jiFenJiaoYiButton addTarget:self action:@selector(didClickJiFenJiaoYiButton) forControlEvents:UIControlEventTouchUpInside];
            [cell.leftBtn addTarget:self action:@selector(xiaofeiBtn) forControlEvents:UIControlEventTouchUpInside];
            [cell.leftBtn setImage:[UIImage imageNamed:@"hy_xiaofei"] forState:UIControlStateNormal];
            [cell.rightBtn addTarget:self action:@selector(didClickRightBuyGouWuQuanButton) forControlEvents:UIControlEventTouchUpInside];
        }
        
        return cell;
    } else if (indexPath.section == 2) {
        ThreeButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ButtonCell" forIndexPath:indexPath];
        if (self.loadUserData.count) {
            
            cell.GouWuQuanLabel.text = [NSString stringWithFormat:@"%.2f",self.gouWuQuanCount.floatValue];
            
            cell.GuQuanJiFenLabel.text = [NSString stringWithFormat:@"%.2f",[[self.loadUserData objectForKey:@"gq_Money"] floatValue]];
            
            cell.GuangGaoLabel.text = [NSString stringWithFormat:@"%.2f",[[self.loadUserData objectForKey:@"Dl_Money"] floatValue]];
            
        } else {
            
            cell.GouWuQuanLabel.text = @"0.00";
            cell.GuangGaoLabel.text = @"0.00";
            cell.GuQuanJiFenLabel.text = @"0.00";
        }
        
        [cell.ShopQuanBtn addTarget:self action:@selector(shopQuanBtn) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mine"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"mine"] ;
        }
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text= self.dataArr[indexPath.row];
        cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"hy_icon_%ld", indexPath.row + 1]];
        return cell;
    }
}

- (void)didClickJiuDianHuiWuButton {
    
    if ([JudgeUserLogInTool  JudgeUserLonInStatus]) {
    JiuDianHuiWuViewController *huiWu = [[JiuDianHuiWuViewController alloc] init];
#warning 会晤跳转
    [self pushForm:self.navigationController pushToAndHidden:huiWu];

    }
}

- (void)didClickJiFenJiaoYiButton {
    
    if ([JudgeUserLogInTool  JudgeUserLonInStatus]) {
        XiaoFeiViewController *xiaoVC = [[XiaoFeiViewController alloc] init];
        
        xiaoVC.GuangGaoFenHongLabel.text = [NSString stringWithFormat:@"%.2f",[[self.loadUserData objectForKey:@"fh_Money"] floatValue]];
        
        [self pushForm:self.navigationController pushToAndHidden:xiaoVC];

    }
}

- (void)reloadHeaderViewData {
    if (self.loadUserData.count) {
        self.headerView.JiHuoZhuangTai.text = @"已激活";
        
        NSString *Time = [self.loadUserData objectForKey:@"LastLoginTime"];
        Time = [Time stringByReplacingOccurrencesOfString:@"T" withString:@" "];
        self.headerView.SuoDingShiJian.text = [NSString stringWithFormat:@"锁定时间: %@",Time];
        
        NSString *userName = [self.loadUserData objectForKey:@"RealName"];
        if ([userName isEqualToString:@""]) {
            self.headerView.NameLabel.text = @"昵称";
        } else {
            self.headerView.NameLabel.text = [userName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        }
        
        self.headerView.HuiYuanZhuangTai.text = [NSString stringWithFormat:@"%@", [self.loadUserData objectForKey:@"UserRole"]];
        
    } else {
        self.headerView.JiHuoZhuangTai.text = @"未激活";
        self.headerView.SuoDingShiJian.text = @"锁定时间: ";
        self.headerView.NameLabel.text = @"昵称";
        self.headerView.HuiYuanZhuangTai.text = @"账户类型";
        
    }

}

#pragma mark - UITableView Delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    

    
    if ([JudgeUserLogInTool  JudgeUserLonInStatus]) {

        if (indexPath.row == 1) {
            //        [self.navigationController pushViewController:[[FenSiZhongXinTableViewController alloc] init] animated:YES];
            [self pushForm:self.navigationController pushToAndHidden:[[FenSiZhongXinTableViewController alloc] init]];
        }
        
        if (indexPath.row == 6 ) {
            jiFenViewController *jifen = [[jiFenViewController alloc] init];
            [self pushForm:self.navigationController pushToAndHidden:jifen];
        }
        
        if (indexPath.row == 2) {
            GetAddressTableViewController *address = [[GetAddressTableViewController alloc] init];
            [self pushForm:self.navigationController pushToAndHidden:address];
        }
        
        if (indexPath.row == 3) {
            MyOrderTableViewController *order = [[MyOrderTableViewController alloc] init];
            
            [self pushForm:self.navigationController pushToAndHidden:order];
        }
        
        
    }else{
        

        
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (void)button{
    
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0 || indexPath.section == 1) {
        return 100;
    }
    return 60;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - cell Button 
    
- (void)zhuanzhangBtn {
    if ([JudgeUserLogInTool  JudgeUserLonInStatus]){
        ZhuanZhangViewController *zzVC = [[ZhuanZhangViewController alloc] init];
                
        [self pushForm:self.navigationController pushToAndHidden:zzVC];

    }
}
// 消费Button
- (void)xiaofeiBtn {
    
   [[NSNotificationCenter defaultCenter] postNotificationName:@"DidClickXiaoFeiButtonChangeTabBarControllerSelected" object:nil userInfo:nil];
}

- (void)buyQuanBtn
{
    if ([JudgeUserLogInTool  JudgeUserLonInStatus]) {
        
        BuyQuanViewController *buyVC = [[BuyQuanViewController alloc] init];
#warning 传入购物券购买Type
        buyVC.buyType = @"0";
        [self pushForm:self.navigationController pushToAndHidden:buyVC];
    }
}

- (void)didClickRightBuyGouWuQuanButton {
 
    if ([JudgeUserLogInTool  JudgeUserLonInStatus]) {
        
        BuyQuanViewController *buyVC = [[BuyQuanViewController alloc] init];
#warning 传入购物券购买Type
        buyVC.buyType = @"1";
        [self pushForm:self.navigationController pushToAndHidden:buyVC];
    }
    
}

- (void)shopQuanBtn
{
    if ([JudgeUserLogInTool  JudgeUserLonInStatus]) {
        ShopQuanViewController *shopVC = [[ShopQuanViewController alloc] init];
        [self pushForm:self.navigationController pushToAndHidden:shopVC];
    }
}

//tabBar 隐藏
- (void)pushForm:(UINavigationController *)pushForm pushToAndHidden:(UIViewController *)pushToVC
{
    [pushToVC setHidesBottomBarWhenPushed:YES];
    [pushForm pushViewController:pushToVC animated:YES];
    
}


@end
